<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">

<head>
    <th:block th:include="include :: header('新增报表')" />
    <style>
        #bootstrap-table tr {
            height: 60px;
        }

        .custom-select {
            position: relative;
            display: inline-block;
            width: 200px;
            /* 设置下拉框的固定宽度 */
            border-radius: 8px;
            /* 圆角矩形 */
        }

        .select-trigger {
            padding: 10px;
            border: 1px solid #ced4da;
            /* 使用 Bootstrap 样式 */
            cursor: pointer;
            position: relative;
            background-color: #fff;
            /* 使用 Bootstrap 样式 */
            border-radius: 8px;
            /* 圆角矩形 */
        }

        .dropdown {
            display: none;
            position: absolute;
            top: 100%;
            left: 0;
            width: 100%;
            max-height: 120px;
            overflow-y: auto;
            border: 1px solid #ccc;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
            z-index: 1;
            background-color: #fff;
            border-radius: 0 0 10px 10px;
            /* 底部圆角 */

        }

        .dropdown-item {
            padding: 10px;
            cursor: pointer;
        }

        .select-trigger:hover {
            box-shadow: 0 0 15px rgba(0, 0, 0, 0.1);
            /* 鼠标悬浮时的阴影效果 */
        }

        .select-trigger:active {
            box-shadow: 0 0 15px rgba(0, 123, 255, 0.4);
            /* 点击时的阴影效果，蓝色阴影 */
        }

        .dropdown-item:hover {
            background-color: #f5f5f5;
        }

        .fixed-table-container {
            height: 240px;
        }

        /* 上述是模拟框的css */
    </style>

</head>

<body class="white-bg">

    <form class="form-horizontal m" id="form-purchasereport-add"></form>
    <table id="bootstrap-table"></table>
    <table class="table table-striped table-hover" id="showTable">

    </table>
    <th:block th:include="include :: footer" />
    <script type="text/javascript">//创建自定义框
        function getOptionPartFirst(id) {
            return `    <div class="custom-select">
        <div class="select-trigger" id="` + id + `" onClick="selectTriggerClick(this)">Select an option</div>
        <div class="dropdown ` + id + `">
          <ul class="list-group">`;
        }

        function getOptionPartMiddle(name, code) {
            return `  <li class="list-group-item dropdown-item" >
              <span >` + name + `</span>
              <span style="color: red;">[b:` + code + `]</span>
              
            </li>`
        }

        function getOptionPartEnd() {
            return `   </ul>
              </div>
              </div>`;
        }

        //  获取编码[b:xxx]
        function getBar(select) {
            var match = /([\w\d\s\u4e00-\u9fa5]+)\[b:(\d+)\]/.exec(select);
            var result = match && match[2];
            // console.log(select, match, result);
            return result;
        }

        function getName(select) {
            var matchResult = /([\w\d\s\u4e00-\u9fa5]+)\[b:(\d+)\]/.exec(select);
            var result = matchResult && matchResult[1];

            return result;
        }

    </script>
    <script th:inline="javascript">//submit的数据
        var prefix = ctx + "system/purchasereport"
        $("#form-purchasereport-add").validate({
            focusCleanup: true
        });


        function submitHandler() {
            if ($.validate.form()) {
                $.ajax({
                    type: 'POST',
                    url: prefix + "/addpurchaseitem",
                    data: JSON.stringify(uploadMap),
                    contentType: 'application/json',
                    success: function (response) {
                        if (response == "success") {
                            alert("添加成功");
                            location.reload();
                        }
                    },
                    error: function (xhr, status, error) {
                        console.error('发送数据失败', error);
                    }
                });
                // alert("点了以下");
            }
        }


    </script>
    <script>

        function hasFinishClass(component) {

            var classes = component.className;
            return classes.split(' ').indexOf('finish') !== -1;
        }

        var selectTrigger = document.querySelector('.select-trigger#id');


        function selectTriggerClick(element) {
            var ss = ".dropdown." + element.id;
            var dropdownList = document.querySelector(ss);
            dropdownList.style.display = (dropdownList.style.display === 'block') ? 'none' : 'block';

            if (!hasFinishClass(dropdownList)) {
                var droplistli = dropdownList.querySelectorAll('ul li');

                droplistli.forEach(e => {
                    e.addEventListener('click', function () {
                        var spanlist = e.getElementsByTagName('span');
                        var text = "";
                        // console.log(spanlist[0].innerText);
                        for (var i = 0; i < spanlist.length; i++) {
                            text += spanlist[i].innerText.trim();
                        }
                        element.innerText = text;

                    });
                });
                dropdownList.classList.add("finish");
            }

        };


    </script>

    <script>//对数据的操作
        let showMap = {};

        let uploadMap = {};

        function additem() {
            var goodsText = document.querySelector("#goods").innerText;
            var supplierText = document.querySelector("#suppliers").innerText;
            var quantity = document.querySelector("#quantity").value;


            if (quantity == 0) {
                alert("商品数量不能为0");
            } else if (goodsText == "Select an option" || supplierText == "Select an option") {
                alert("不允许不选择");
            } else {//进行验证
                var goodsBarCode = getBar(goodsText);
                var goodsName = getName(goodsText);
                var supplierCode = getBar(supplierText);
                var supplierName = getName(supplierText);
                var key = goodsBarCode + "&&" + supplierCode;
                if (goodsBarCode == null || goodsName == null || supplierCode == null || supplierName == null) {
                    alert("数据发生错误")
                } else {
                    if (key in uploadMap)//有键增加数量
                    {
                        uploadMap[key] = Number(uploadMap[key]) + Number(quantity);
                        showMap[key]["quantity"] = Number(showMap[key]["quantity"]) + Number(quantity);
                    } else {
                        showMap[key] = {
                            "goodsBarCode": goodsBarCode,
                            "goodsName": goodsName,
                            "supplierCode": supplierCode,
                            "supplierName": supplierName,
                            "quantity": quantity
                        };
                        uploadMap[key] = quantity;
                    }
                }
            }


            updateShowTable()
        }

        function updateShowTable() {
            var table = document.querySelector("#showTable");
            table.innerHTML = "";//置空
            var trHead = document.createElement("tr");
            trHead.innerHTML = ` <tr>
        
        <th class="table-secondary">序号</th>
        <th class="table-secondary">商品编码</th>
        <th class="table-secondary">商品名</th>
        <th class="table-secondary">供应商编号</th>
        <th class="table-secondary">供应商名</th>
       
        <th class="table-secondary">订购数量</th>
      </tr>`

            table.append(trHead);
            var i = 0;
            for (var key in showMap) {
                var tr = document.createElement("tr");
                i = i + 1;
                tr.innerHTML = `
        <tr>
        <th class="table-secondary">` + i + `</th>
        <th class="table-secondary">` + showMap[key]['goodsBarCode'] + `</th>
        <th class="table-secondary">` + showMap[key]['goodsName'] + `</th>
        <th class="table-secondary">` + showMap[key]['supplierCode'] + `</th>
        <th class="table-secondary">` + showMap[key]['supplierName'] + `</th>
        <th class="table-secondary">` + showMap[key]['quantity'] + `</th>
      </tr>
        `
                table.append(tr);
            }
        }


    </script>

    <script th:inline="javascript">//table初始化数据
        var addFlag = [[${@permission.hasPermi('system:purchasereport:add') }]];
        var prefix = ctx + "system/purchasereport";

        $(function () {
            var options = {
                url: prefix + "/add",
                modalName: "增加报表",
                columns: [{
                    checkbox: true
                },
                {
                    field: 'reportId',
                    title: '选择商品',
                    formatter: function (value, row, index) {
                        var actions = [];
                        var option = "";
                        console.log(row.goodsInforList);
                        var list = row.goodsInforList;
                        option += getOptionPartFirst("goods")
                        list.forEach(e => {
                            option += getOptionPartMiddle(e.name, e.barCode)
                        });
                        option += getOptionPartEnd()
                        actions.push(option);

                        return actions.join('');
                    }
                },
                {
                    field: 'supplierName',
                    title: '选择供应商',
                    formatter: function (value, row, index) {
                        var actions = [];
                        var option = "";
                        console.log(row.suppliersList);
                        var list = row.suppliersList
                        option += getOptionPartFirst("suppliers")
                        list.forEach(e => {
                            option += getOptionPartMiddle(e.name, e.supplierId)
                        })
                        option += getOptionPartEnd()
                        actions.push(option);
                        return actions.join('');
                    }
                },
                {
                    field: 'purchaseReportId',
                    title: '输入需要上报数量',
                    formatter: function (value, row, index) {
                        var actions = [];
                        actions.push(`      <input type="number" min="0" value="0" id="quantity">`);
                        return actions.join('');
                    }
                }, {
                    title: '操作',
                    align: 'center',
                    formatter: function (value, row, index) {
                        var actions = [];
                        actions.push(`<a class="btn btn-success btn-xs " href="javascript:void(0)" onclick="additem()"><i class="fa fa-edit"></i>添加商品</a> `);

                        return actions.join('');
                    }
                }
                ]
            };
            $.table.init(options);

        });
    </script>
</body>

</html>